<template>
  <div class="dashboard-container">
    <!-- 顶部统计卡片 -->
    <div class="stat-cards">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-title">总销售额</div>
            <div class="stat-value">¥ {{ dashboardData.dashboardSaleVO ? dashboardData.dashboardSaleVO.totalSalesPrice.toFixed(2) : '0.00' }}</div>
            <div class="stat-compare">
              <span class="up">近30日</span>
            </div>
          </div>
          <div class="stat-icon">
            <i class="el-icon-money"></i>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-title">订单数量</div>
            <div class="stat-value">{{ dashboardData.dashboardSaleVO ? dashboardData.dashboardSaleVO.totalOrders : 0 }}</div>
            <div class="stat-compare">
              <span class="up">近30日</span>
            </div>
          </div>
          <div class="stat-icon">
            <i class="el-icon-s-order"></i>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-title">库存总量</div>
            <div class="stat-value">{{ dashboardData.dashboardSaleVO ? dashboardData.dashboardSaleVO.totalStockNumber : 0 }}</div>
            <div class="stat-compare">
              <span class="up">库存充足</span>
            </div>
          </div>
          <div class="stat-icon">
            <i class="el-icon-box"></i>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-title">出库比例</div>
            <div class="stat-value">{{ dashboardData.dashboardSaleVO ? dashboardData.dashboardSaleVO.amountPercentage.toFixed(2) : '0.00' }}%</div>
            <div class="stat-compare">
              <span class="up">出库占比</span>
            </div>
          </div>
          <div class="stat-icon">
            <i class="el-icon-user"></i>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="chart-section">
      <el-row :gutter="20">
        <el-col :span="15">
          <el-card class="chart-card">
            <div slot="header" class="chart-header">
              <span>销售趋势</span>
            </div>
            <div class="chart-content" ref="lineChart"></div>
          </el-card>
        </el-col>
        <el-col :span="9">
          <el-card class="chart-card">
            <div slot="header" class="chart-header">
              <span>销售分类</span>
            </div>
            <div class="chart-content" ref="pieChart"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 订单列表 -->
    <div class="order-section">
      <el-card class="order-card">
        <div slot="header" class="order-header">
          <span>最新订单</span>
          <el-button type="text" @click="goToOrders">查看更多</el-button>
        </div>
        <el-table :data="dashboardData.orderVOList || []" style="width: 100%">
          <el-table-column prop="code" label="订单号" width="250" align="center"></el-table-column>
          <el-table-column prop="operatorName" label="操作员" width="200" align="center"></el-table-column>
          <el-table-column prop="price" label="金额" width="160" align="center">
            <template slot-scope="scope">
              ¥{{ scope.row.price.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="totalNumber" label="商品总数" width="160" align="center"></el-table-column>
          <el-table-column prop="status" label="状态" width="160" align="center">
            <template slot-scope="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="250" align="center">
            <template slot-scope="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'DashboardView',
  data() {
    return {
      timeRange: 'month',
      dashboardData: {},
      loading: false
    }
  },
  mounted() {
    this.fetchDashboardData()
  },
  methods: {
    fetchDashboardData() {
      this.loading = true;
      this.$http.get('/dashboard')
        .then(response => {
          if (response.code === 200) {
            this.dashboardData = response.data;
            this.$nextTick(() => {
              this.initLineChart();
              this.initPieChart();
            });
          }
          // 错误会由全局拦截器处理
        })
        .catch(error => {
          console.error('获取数据失败:', error);
          // 错误会由全局拦截器处理
        })
        .finally(() => {
          this.loading = false;
        });
    },
    initLineChart() {
      if (!this.dashboardData.salesTrendVO) return;
      
      const lineChart = echarts.init(this.$refs.lineChart)
      
      const dates = this.dashboardData.salesTrendVO.map(item => {
        const date = new Date(item.date);
        return `${date.getMonth() + 1}-${date.getDate()}`;
      });
      
      const saleAmounts = this.dashboardData.salesTrendVO.map(item => item.saleAmount);
      const orderCounts = this.dashboardData.salesTrendVO.map(item => item.orderCount);
      
      const option = {
        color: ['#ff6b00', '#304156'],
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['销售额', '订单数']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates
        },
        yAxis: [
          {
            type: 'value',
            name: '销售额',
            position: 'left',
            axisLabel: {
              formatter: '{value} 元'
            }
          },
          {
            type: 'value',
            name: '订单数',
            position: 'right',
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [
          {
            name: '销售额',
            type: 'line',
            smooth: true,
            yAxisIndex: 0,
            data: saleAmounts
          },
          {
            name: '订单数',
            type: 'line',
            smooth: true,
            yAxisIndex: 1,
            data: orderCounts
          }
        ]
      }
      lineChart.setOption(option)
      
      // 添加窗口调整大小的事件监听
      window.addEventListener('resize', () => {
        lineChart.resize();
      });
    },
    initPieChart() {
      if (!this.dashboardData.categorySalesVO) return;
      
      const pieChart = echarts.init(this.$refs.pieChart)
      
      const pieData = this.dashboardData.categorySalesVO.map(item => ({
        name: item.categoryName,
        value: item.totalAmount
      }));
      
      const option = {
        color: ['#9C27B0', '#00BCD4', '#4CAF50', '#FFEB3B', '#FF9800', '#F44336'],
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: pieData.map(item => item.name)
        },
        series: [
          {
            name: '销售分类',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '20',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: pieData
          }
        ]
      }
      pieChart.setOption(option)
      
      // 添加窗口调整大小的事件监听
      window.addEventListener('resize', () => {
        pieChart.resize();
      });
    },
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString();
    },
    getStatusType(status) {
      const statusMap = {
        'pending': 'warning',
        'processing': 'primary',
        'completed': 'success',
        'cancelled': 'info'
      };
      return statusMap[status] || 'info';
    },
    getStatusText(status) {
      const statusMap = {
        'pending': '待处理',
        'processing': '处理中',
        'completed': '已完成',
        'cancelled': '已取消'
      };
      return statusMap[status] || status;
    },
    goToOrders() {
      this.$router.push({
        path: '/sales/orders',
        query: { t: Date.now() } // 添加时间戳参数强制刷新
      });
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background: #f0f2f5;
  min-height: 100vh;
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
}

.stat-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
}

.stat-info {
  flex-grow: 1;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.stat-compare {
  font-size: 12px;
}

.up {
  color: #67c23a;
}

.down {
  color: #f56c6c;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  background: #ff6b00;
  display: flex;
  justify-content: center;
  align-items: center;
}

.stat-icon i {
  font-size: 24px;
  color: #fff;
}

.chart-section {
  margin-bottom: 20px;
}

.chart-card {
  border-radius: 8px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #304156;
}

.chart-content {
  height: 350px;
}

.order-card {
  border-radius: 8px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 覆盖 Element UI 的主题色 */
:deep(.el-button--primary) {
  background-color: #ff6b00;
  border-color: #ff6b00;
}

:deep(.el-button--primary:hover),
:deep(.el-button--primary:focus) {
  background-color: #ff8533;
  border-color: #ff8533;
}

:deep(.el-radio-button__orig-radio:checked + .el-radio-button__inner) {
  background-color: #ff6b00;
  border-color: #ff6b00;
}

:deep(.el-tag--success) {
  background-color: rgba(255, 107, 0, 0.1);
  border-color: rgba(255, 107, 0, 0.2);
  color: #ff6b00;
}

.el-card {
  border-radius: 8px;
  margin-bottom: 20px;
}

.el-card__header {
  padding: 15px 20px;
  border-bottom: 1px solid #e6e6e6;
  color: #304156;
}

.el-table {
  color: #304156;
}

.el-table th {
  background-color: #f5f7fa;
  color: #304156;
}
</style> 